package tungsten.pb;

import com.google.protobuf.MessageLite;
import com.google.protobuf.MessageLiteOrBuilder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import tungsten.base.utils.ByteUtils;
import tungsten.pb.protocol.Heads;

import java.util.List;

import static io.netty.buffer.Unpooled.wrappedBuffer;

/**
 * Created by Lv on 2016/6/24.
 */
public class PBEncoder extends MessageToMessageEncoder<PBMessage>
{
    @Override
    protected void encode(ChannelHandlerContext ctx, PBMessage msg, List<Object> out) throws Exception
    {
        Heads.Head.Builder builder = Heads.Head.newBuilder().setModuleId(msg.getModuleId()).setBytes(msg.getMessage().toByteString());
        builder.setCrc32(ByteUtils.crc32(builder.getBytes().toByteArray()));
        out.add(wrappedBuffer(builder.build().toByteArray()));
    }
}